package com.base.security;

import javax.security.auth.login.LoginException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import com.base.domain.User;
import com.base.service.UserService;


public class CustomAuthenticationProvider implements AuthenticationProvider {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
	
	private UserService userService;
	
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {		
		UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

		String username = userToken.getName();
		if(StringUtils.isEmpty(username)){
			LOGGER.error("Usuario Vacio");
            throw new BadCredentialsException("Usuario vacio");			
		}
		
		String password = (String)userToken.getCredentials();
		if(StringUtils.isEmpty(username)){
			LOGGER.error("Password vacia");
            throw new BadCredentialsException("Password vacia");			
		}		

		User user;
		try {
			user = userService.login(username, password);
		} catch (LoginException e) {
			LOGGER.error(e.getMessage());
			throw new BadCredentialsException("Credenciales erroneas");
		}  
		
		
        return new CustomUsernamePasswordAuthenticationToken(username, password, user.getRoles(), user);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}

}

